package com.gitee.feizns.explore.data_structure.union_find;

/**
 * @author feizns
 * @since 2020/3/11
 */
public class FindCircleNum {

    public static void main(String[] args) {

    }

    public static int findCircleNum(int[][] M) {
        Uf uf = new Uf(M.length);
        for (int i = 0; i < M.length; i++) {
            for (int j = 0; j < i + 1; j++) {
                if ( M[i][j] == 1 )
                    uf.union(i, j);
            }
        }
        return uf.count;
    }

    static class Uf {
        int[] parents;
        int count;
        public Uf(int size) {
            parents = new int[size];
            count = size;
            for (int i = 0; i < size; i++)
                parents[i] = i;
        }
        public void union(int q, int p) {
            int qr = find(q);
            int pr = find(p);
            if ( qr != pr ) {
                parents[qr] = pr;
                count--;
            }
        }
        public int find(int q) {
            while ( q != parents[q] ) {
                parents[q] = parents[parents[q]];
                q = parents[q];
            }
            return q;
        }
    }

}
